package com.sumainfor.pc.epc.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.MoSupplierObject;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.MoSupplierObjectUtil;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.epc.dao.BuyerManageMapper;
import com.sumainfor.pc.epc.dao.SettlementManageMapper;
import com.sumainfor.pc.epc.dao.StockManageMapper;
import com.sumainfor.pc.epc.dao.SupplierManageMapper;
import com.sumainfor.pc.epc.service.SupplierManageService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author PuaChen
 * @Create 2018-11-22 9:55
 * 供应商
 */
@Service
@Log4j2
@Transactional(rollbackFor = Exception.class)
public class SupplierManageServiceImpl implements SupplierManageService {

    @Autowired
    private SupplierManageMapper supplierManageMapper;

    @Autowired
    private BuyerManageMapper buyerManageMapper;

    @Autowired
    private StockManageMapper stockManageMapper;

    @Autowired
    private SettlementManageMapper settlementManageMapper;

    /**
     * 返回所有的供应商的类型
     *
     * @return
     */
    @Override
    public JsonResult getSupplierTypes() {
        List<CustomMap> list = Lists.newArrayList();
        for (Map.Entry<String, Object> entry : Constants.SupplierTypeConst.TYPE_MAP.entrySet()) {
            list.add(CustomMap.create("id", entry.getKey())
                    .put("name", entry.getValue()));
        }
        return JsonResult.success(list);
    }

    /**
     * 获取所有供应商的信息
     * 可以查询条件根据 type 类型区分 硬装还是软装
     * 和根据 时间进行区分 date
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult getSupplierDataList(Page page, Map<String, Object> params) {
        IPage<Map<String, Object>> response = supplierManageMapper.selectSupplierList(page, params);
        response.setRecords(response.getRecords().stream().map(item -> {
            if (ShopTypeSelectUtil.isSupplierTypeIsYZ(MapUtils.getString(item, "SupType"))) {
                //如果是硬装的话 查询收费类型数据
                List<Map<String, Object>> priceConf = supplierManageMapper.selectSupplierPriceBySupId(MapUtils.getString(item, "SupId"));
                item.put("PriceConfig", priceConf);
            }
            item.put("SupTypeName", ShopTypeSelectUtil.selectSupplierTypeById(MapUtils.getString(item, "SupType")));
            return item;
        }).collect(Collectors.toList()));
        return JsonResult.success(response);
    }

    /**
     * 获得绑定商品列表数据
     * 条件
     * type  类别
     * shopName  商品的名称
     * brand 商品的品牌
     * supId 供应商的ID 必须参数
     *
     * @param params
     * @param page   分页
     * @return
     */
    @Override
    public JsonResult selectBindShopList(Page page, Map<String, Object> params) {
        String supId = MapUtils.getString(params, "supId");
        Map<String, Object> supplierOne = supplierManageMapper.getSupplierOne(supId);
        if (supplierOne == null || supplierOne.isEmpty()) {
            return JsonResult.error("没有这个供应商");
        }
        String moId = MapUtils.getString(supplierOne, "ComSpeMoId", "");

        String[] split = moId.split(",");
        List<String> list = Lists.newArrayList(split);
        log.info("selectBindShopList ==> params list = {}", list);
        IPage<Map<String, Object>> response = supplierManageMapper.selectBindShopMoList(page, list, params);
        response.setRecords(response.getRecords().stream().map(item -> {
            item.put("ComTypeFlag", item.get("ComType"));
            item.put("ComType", ShopTypeSelectUtil.selectShopTypeById(MapUtils.getString(item, "ComType")));
            //拿出单价 库存数
            List<MoSupplierObject> supplier = MoSupplierObjectUtil.convertJsonToList(MapUtils.getString(item, "supplier"));
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(supplier)) {
                MoSupplierObject dat = MoSupplierObjectUtil.selectSupplierById(supplier, supId);
                item.put("Price", dat.getPrice());
                item.put("count", dat.getStoreCount());
            }
            item.remove("supplier");
            return item;
        }).collect(Collectors.toList()));
        return JsonResult.success(response);
    }

    /**
     * 根据供应商的编号去查询采购记录信息
     * 参数:
     * supId 必须参数
     * shopName 商品名称
     * date 时间
     *
     * @param page
     * @param params
     * @return
     */
    @Override
    public JsonResult buyerLogs(Page page, Map<String, Object> params) {
        IPage<Map<String, Object>> data = supplierManageMapper.selectBuyerLogsBySupplierId(page, params);
        for (Map<String, Object> map : data.getRecords()) {
            List<MoSupplierObject> list = MoSupplierObjectUtil.convertJsonToList(MapUtils.getString(map, "supplier"));
            MoSupplierObject suMo = MoSupplierObjectUtil.selectSupplierById(list, MapUtils.getString(params, "supId"));
            if (suMo == null) {
                throw new TCException("商品没有这个供应商数据有误");
            }
            map.remove("supplier");
            map.put("price", suMo.getPrice());
            map.put("ComType", ShopTypeSelectUtil.selectShopTypeById(MapUtils.getString(map, "ComType")));
            DateUtils.formatDateByMap(map);
        }
        return JsonResult.success(data);
    }

    /**
     * 修改供应商的基本信息
     *
     * @param params
     * @return
     */
    @Override
    @SuppressWarnings("all")
    public JsonResult updateSupplierBaseData(Map<String, Object> params) {

        Map<String, Object> supMain = supplierManageMapper.getSupplierOne((String) params.get("SupId"));
        if (MapUtils.isEmpty(supMain)) {
            return JsonResult.error("没有查询到这个供应商的信息");
        }

        Map<String, Object> map = ParamsCommon.commonUpdateParms(CustomMap.create()
                        .put("SupId", params.get("SupId"))
                        .put("UnitName", params.get("UnitName"))
                        .put("Contact", params.get("Contact"))
                        .put("Phone", params.get("Phone"))
                        .put("Address", params.get("Address"))
                        .put("Adjunct", params.get("Adjunct"))
                        .put("Corp", params.get("Corp"))
                        .put("TariffItem", params.get("TariffItem"))
                        .put("Bank", params.get("Bank"))
                        .put("TaxRate", params.get("TaxRate"))
                        .put("AccountName", params.get("AccountName"))
                        .put("Account", params.get("Account"))
                        .put("AccountBank", params.get("AccountBank"))
                        .put("delfg", params.get("delfg"))
                , getClass());
        if (ShopTypeSelectUtil.isActivitySupplierForBase(MapUtils.getString(params, "SupType"))) {
            //需要添加商品的
            if (StringUtils.isNotBlank(MapUtils.getString(params, "bindShop"))) {
                List<Map<String, Object>> bindShop = (List<Map<String, Object>>) MapUtils.getObject(params, "bindShop");
                if (bindShop != null && !bindShop.isEmpty()) {
                    //累计出来的ID集合 用,分割
                    StringBuffer sb = new StringBuffer();
                    for (Map<String, Object> shop : bindShop) {
                        if (!FieldCheckUtil.isMapFieldNotNull(shop, "moId", "price")) {
                            throw new TCException("商品的参数不完整");
                        }
                        String moId = MapUtils.getString(shop, "moId");
                        sb.append(moId).append(",");

                        //获取商品的信息
                        Map<String, Object> moInfo = stockManageMapper.getShopMoForInfos(moId);
                        if (moInfo == null || moInfo.isEmpty()) {
                            throw new TCException("查询不到这个型号");
                        }

                        List<MoSupplierObject> moToSupList = MoSupplierObjectUtil.convertJsonToList(MapUtils.getString(moInfo, "supplier"));
                        if (moToSupList == null || moToSupList.isEmpty()) {
                            moToSupList = Lists.newArrayList();
                        }

                        //查询是否能够查询到这个商品信息
                        MoSupplierObject supMoObj = MoSupplierObjectUtil.selectSupplierById(moToSupList, MapUtils.getString(params, "SupId"));
                        if (supMoObj == null) {
                            //新增
                            int errorCount = 1;
                            supMoObj = new MoSupplierObject();
                            supMoObj.setPrice(new BigDecimal(MapUtils.getString(shop, "price")));
                            supMoObj.setErrorCount(errorCount);
                            supMoObj.setSupplierId(MapUtils.getString(params, "SupId"));
                            supMoObj.setStoreCount(0);
                            moToSupList.add(supMoObj);
                            //更新商品操作
                        } else {
                            //修改
                            supMoObj.setPrice(new BigDecimal(MapUtils.getString(shop, "price")));
                        }
                        moInfo.put("supplier", MoSupplierObjectUtil.toJson(moToSupList));
                        int i = buyerManageMapper.updateShopForMo(ParamsCommon.commonUpdateParms(moInfo, getClass()));
                        if (i <= 0) {
                            throw new TCException("操作商品失败");
                        }
                    }
                    //查询有删除的 让其移除掉
                    ArrayList<String> newMoIds = Lists.newArrayList(sb.toString().split(","));
                    //查询原先的
                    ArrayList<String> oldIds = Lists.newArrayList(MapUtils.getString(supMain, "ComSpeMoId").split(","));
                    oldIds.removeAll(newMoIds);
                    //循环移除操作
                    for (int i = 0; i < oldIds.size(); i++) {
                        String moId = oldIds.get(i);
                        //获取商品的信息
                        Map<String, Object> moInfo = stockManageMapper.getShopMoForInfos(moId);
                        if (moInfo == null || moInfo.isEmpty()) {
                            throw new TCException("查询不到这个型号");
                        }

                        List<MoSupplierObject> moToSupList = MoSupplierObjectUtil.convertJsonToList(MapUtils.getString(moInfo, "supplier"));
                        if (moToSupList == null || moToSupList.isEmpty()) {
                            throw new TCException("型号供应商信息获取失败");
                        }
                        //查询是否能够查询到这个商品信息
                        MoSupplierObject supMoObj = MoSupplierObjectUtil.selectSupplierById(moToSupList, MapUtils.getString(params, "SupId"));
                        if (supMoObj == null) {
                            throw new TCException("数据异常");
                        }
                        moToSupList.remove(supMoObj);
                        moInfo.put("supplier", MoSupplierObjectUtil.toJson(moToSupList));
                        int row = buyerManageMapper.updateShopForMo(ParamsCommon.commonUpdateParms(moInfo, getClass()));
                        if (row <= 0) {
                            throw new TCException("操作商品失败");
                        }
                    }
                    map.put("ComSpeMoId", sb.toString());
                }
            }
        }
        int row = supplierManageMapper.updateSupplier(map);
        if (row <= 0) {
            throw new TCException("修改失败");
        }
        return JsonResult.success();
    }

    /**
     * 查询打款记录
     *
     * @param page
     * @param params RemState 审核状态 状态  1确认中  2.被驳回  3.已确认
     *               StaCut 账单类型 账单类型 1.装修结算单,2备件结算单,3.保洁结算单,4.硬装结算单
     *               Date 时间筛选
     * @return
     */
    @Override
    public JsonResult selectPutPriceLog(Page page, Map<String, Object> params) {
        return JsonResult.success(settlementManageMapper.selectOutPriceLogBySupId(page, params));
    }

    /**
     * 获得 所有的采购单类型 下拉列表数据
     *
     * @return
     */
    @Override
    public JsonResult getBuyerType() {
        List<CustomMap> data = Lists.newArrayList();
        for (Map.Entry<String, Object> entry : Constants.BuyerTypeConst.TYPE_MAP.entrySet()) {
            data.add(CustomMap.create("name", entry.getValue())
                    .put("id", entry.getKey()));
        }
        return JsonResult.success(data);
    }

    /**
     * 创建供应商
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult createSupplier(Map<String, Object> params) {
        String type = MapUtils.getString(params, "SupType");
        String supId = MapUtils.getString(params, "SupId");

        //这里进行查询是否有重复的ID 编号
        int count = supplierManageMapper.getSupplierIdCount(supId);
        if (count > 0) {
            return JsonResult.error("供应商的编号已被使用");
        }

        //判断是否需要添加绑定商品的操作
        if (ShopTypeSelectUtil.isActivitySupplierForBase(type)) {
            //需要添加商品的列表
            if (FieldCheckUtil.isMapFieldNotNull(params, "bindShop") && CollectionUtils.isNotEmpty((Collection) MapUtils.getObject(params, "bindShop"))) {
                List<Map<String, Object>> bindShop = (List<Map<String, Object>>) MapUtils.getObject(params, "bindShop");
                if (bindShop == null || bindShop.isEmpty()) {
                    return JsonResult.error("没有绑定的商品");
                }
                //累计出来的ID集合 用,分割
                StringBuffer sb = new StringBuffer();
                for (Map<String, Object> map : bindShop) {
                    if (!FieldCheckUtil.isMapFieldNotNull(map, "moId", "price")) {
                        throw new TCException("商品的参数不完整");
                    }
                    String moId = MapUtils.getString(map, "moId");

                    //获取商品的信息
                    Map<String, Object> moInfo = stockManageMapper.getShopMoForInfos(moId);
                    if (moInfo == null || moInfo.isEmpty()) {
                        throw new TCException("查询不到这个型号");
                    }

                    List<MoSupplierObject> moToSupList = MoSupplierObjectUtil.convertJsonToList(MapUtils.getString(moInfo, "supplier"));
                    if (moToSupList == null || moToSupList.isEmpty()) {
                        throw new TCException("型号供应商信息获取失败");
                    }
                    int errorCount = moToSupList.get(0).getErrorCount();

                    sb.append(moId).append(",");
                    MoSupplierObject mo = new MoSupplierObject();
                    mo.setPrice(new BigDecimal(MapUtils.getString(map, "price")));
                    mo.setErrorCount(errorCount);
                    mo.setSupplierId(supId);
                    mo.setStoreCount(0);
                    moToSupList.add(mo);
                    //更新商品操作
                    moInfo.put("supplier", MoSupplierObjectUtil.toJson(moToSupList));
                    int i = buyerManageMapper.updateShopForMo(ParamsCommon.commonUpdateParms(moInfo));
                    if (i <= 0) {
                        throw new TCException("绑定商品失败");
                    }
                }
                //操作供应商的表
                params.remove("bindShop");
                params.put("ComSpeMoId", sb.toString());
            }
        }
        if (type.equals("1")) {
            //是硬装 生成 硬装供应商-收费套型
            //收费套型类型  1毛坯   2拆装   3精致（硬装供应商才有）
            //需要的参数  SupT1 毛坯  SupT2、 SupT3
            //价格 SupT1Price SupT2Price SupT3Price
            String[] filed = {"SupT1Price", "SupT2Price", "SupT3Price"};
            if (!FieldCheckUtil.isMapFieldNotNull(params, filed)) {
                throw new TCException("请提供硬装参考价");
            }
            int i = supplierManageMapper.insertSupplierPrice(ParamsCommon.commonInsertParms(CustomMap.create()
                            .put("SupId", supId)
                            .put("SupsTypeId", UUIDUtils.generatePrefixUuid("SUP_PRICE"))
                            .put("SupsType", 1)
                            .put("SupsPrice", params.get("SupT1Price"))
                    , getClass()));
            if (i <= 0) {
                throw new TCException("创建失败");
            }

            supplierManageMapper.insertSupplierPrice(ParamsCommon.commonInsertParms(CustomMap.create()
                            .put("SupId", supId)
                            .put("SupsTypeId", UUIDUtils.generatePrefixUuid("SUP_PRICE"))
                            .put("SupsType", 2)
                            .put("SupsPrice", params.get("SupT2Price"))
                    , getClass()));
            if (i <= 0) {
                throw new TCException("创建失败");
            }

            supplierManageMapper.insertSupplierPrice(ParamsCommon.commonInsertParms(CustomMap.create()
                            .put("SupId", supId)
                            .put("SupsTypeId", UUIDUtils.generatePrefixUuid("SUP_PRICE"))
                            .put("SupsType", 3)
                            .put("SupsPrice", params.get("SupT3Price"))
                    , getClass()));
            if (i <= 0) {
                throw new TCException("创建失败");
            }
        }
        int row = supplierManageMapper.insertSupplier(ParamsCommon.commonInsertParms(params, getClass()));
        if (row <= 0) {
            throw new TCException("创建供应商失败");
        }
        return JsonResult.success();
    }


    /**
     * 获得 所有的采购记录中 商品名称列表 初始化下拉列表
     *
     * @param supId
     * @return
     */
    @Override
    public JsonResult getBuyerShopNames(String supId) {
        return JsonResult.success(supplierManageMapper.getBuyerShopNames(supId));
    }

    /**
     * 功能描述:
     * 获取所有的供应商列表
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/7/3 11:56
     */
    @Override
    public List<Map<String, Object>> getSupplierList() {
        return supplierManageMapper.getSupplierList();
    }

    /**
     * 功能描述:
     * 获取工程部结算单申请打款所有的供应商列表
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/7/3 12:15
     */
    @Override
    public List<Map<String, Object>> getStatementSupplierList() {
        return supplierManageMapper.getStatementSupplierList();
    }
}
